<template>
	<view class="content">
		<!-- #ifdef MP-WEIXIN -->
		<view class="p-x-15 p-y-15 bs-bx" style="background-color: #fff;position: fixed;width: 100%;top: 0%;left: 0%;z-index: 100;">
			<view class="flex-a">
				<uv-search placeholder="请输入订单号" style="flex:1;" @search="searchChanmge" @custom="customChange" v-model="seahData"></uv-search>
				<view class="m-l-20 flex-column1" @click="focus">
					<uv-icon name="calendar" size="25"></uv-icon>
					<text class="size-20" style="color: #999;">选择日期</text>
				</view>
			</view>
			<view class="m-t-10 flex-b p-y-15" style="overflow-x: auto;">
				<view @click="clickList(item)" :class="curerentIndex==item.id?'fw':''" class="size-30 flex-column" v-for="(item,index) in list" :key="index">
					{{item.name}}
					<view v-if="curerentIndex==item.id" class="w-50 h-5 m-t-10 radius-10" style="background-color: #ff7218;">
						
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<view class="p-x-15 p-y-15 bs-bx" style="background-color: #fff;position: fixed;width: 100%;top: 0%;left: 0%;z-index: 100;">
			<view class="flex-a">
				<uv-search placeholder="请输入订单号" style="flex:1;" @search="searchChanmge" @custom="customChange" v-model="seahData"></uv-search>
				<view class="m-l-20 flex-column1" @click="focus">
					<uv-icon name="calendar" size="25"></uv-icon>
					<text class="size-20" style="color: #999;">选择日期</text>
				</view>
			</view>
			<view class="m-t-10 flex-b p-y-15" style="overflow-x: auto;">
				<view @click="clickList(item)" :class="curerentIndex==item.id?'fw':''" class="size-30 flex-column" v-for="(item,index) in list" :key="index">
					{{item.name}}
					<view v-if="curerentIndex==item.id" class="w-50 h-5 m-t-10 radius-10" style="background-color: #ff7218;">
						
					</view>
				</view>
				
			</view>
		</view>
		<!-- #endif -->
		<view v-if="grabOrderList.length>0" class="m-t-190">
			<view class="m-t-20 p-x-20 p-y-20" style="background-color: #fff;" v-for="(item,index) in grabOrderList" @click="toReport(item)" :key="index">
				<view class="flex-b">
					<view class="flex-a">
						<image class="w-50 h-50 m-r-10" src="../../static/image/iconRx.png" mode=""></image>
						<view class="m-l-10" style="color: #999; font-size: 28rpx;">
							{{item.orderId}}
						</view>
					</view>
					<!-- <view class="">
						{{item.orderId}}
					</view> -->
					<text class="size-28" style="color: #ff7218;" v-if="item.currentStatus == 0">待上报</text>
					<text class="size-28" style="color: #ff7218;" v-else-if="item.currentStatus == 1">待结算</text>
					<text class="size-28" style="color: #ff7218;" v-else-if="item.currentStatus == 2">已完成</text>
					<text class="size-28" style="color: #ff7218;" v-else-if="item.currentStatus == 3">已关闭</text>
					<text class="size-28" style="color: #ff7218;" v-else-if="item.currentStatus == 4">纠纷中</text>
					<text class="size-28" style="color: #ff7218;" v-else-if="item.currentStatus == 5">已过期</text>
				</view>
				<view v-if="item.currentStatus==0 && item.showCountdown" class="size-28 text-r" style="color: #999;">
					剩余：<text style="color: red;">{{ Math.floor(item.countdown / 1000) }} 秒</text>
				</view>
				<view class="flex">
					<view class="m-r-20">
						<image class="w-150 h-150" :src="item.productImg" mode=""></image>
					</view>
					<view class="f1 flex-column2">
						<view class="flex-column3">
							<view class="flex-b">
								<view class="eps" style="width: 400rpx;font-weight: 600;">{{item.productName}}</view>
								<view class="bold">
									<text class="size-22">￥</text>
									<text>{{item.settlementAmount}}</text>
								</view>
							</view>
							<view class="m-t-5 flex-b">
								<view class="size-28" style="width: 400rpx;">
									<!-- {{item.orderUserDto.storeName}} -->
								</view>
								×1
							</view>
						</view>
						
						<view class="flex-a" style="align-self: flex-end;" v-if="item.currentStatus=='0'">
							<view @click="report(item)" class="bold size-28 p-x-10 p-y-3 radius-5 m-r-20" style="background-color: #ff72182e;display: inline-block;color: #ff7218;">
								去上报
							</view>
							<view @click="orderFailedTo(item)" class="bold size-28 p-x-10 p-y-3 radius-5" style="background-color: red;display: inline-block;color: white;">
								下单失败
							</view>
						</view>
						
						<!-- <view class="" style="align-self: flex-end;" v-if="item.currentStatus=='4'">
							<view @click="toReport(item)" class="bold size-28 p-x-10 p-y-3 radius-5" style="background-color: #ff72182e;display: inline-block;color: #ff7218;">
								{{item.status}}
							</view>
						</view> -->
						
						<!-- <view class="size-23" style="color: #616161;" v-if="item.currentStatus == '1'">
							结算时间: {{item.nextCheckTime}}
						</view> -->
					</view>
				</view>
			</view>
		</view>
		<view class="po-a po-atl" v-else>
			<view class="text-c">
				<image class="w-200 h-200" src="../../static/image/noProduct.png" mode=""></image>
				<view class="size-32 color-gray">
					订单内容为空~
				</view>
			</view>
		</view>
		<!-- 日期 -->
		<uv-datetime-picker ref="datetimePicker" v-model="data" mode="date" :closeOnClickOverlay="closeOnClickOverlay" @confirm="confirm" @cancel="cancel">
		</uv-datetime-picker>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		toRefs,
		onMounted,
		nextTick,
		onUnmounted
	} from "vue";
	import {
		onLoad,
		onReachBottom,
		onShow,
		onLaunch,
		onReady,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {dataGong,sortJsonKeys,sortAndFormatParams,combine} from '@/utils/encryption.js'
	import {grabList,orderFailed} from '@/api/grab/grab.js'
	
	let scprllHeight  = ref(88)
	let isRefresher = ref(false)
	let datetimePicker = ref(null)
	const data = ref(Date.now());
	let dataSelst = ref()
	let closeOnClickOverlay = ref(true)
	let maxHeight = ref(210)
	let seahData = ref('')
	let suffixIconStyle = ref({
		'color': '#0078d4',
		'fontSize':'45rpx'
	})
	let activeStyle = ref({
		'color': '#000',
		'fontWeight':'bold' 
	})
	let list = ref([{
		id:0,
		name: '全部',
	}, {
		id:1,
		name: '待上报',
	}, {
		id:2,
		name: '待结算'
	}, {
		id:3,
		name: '已完成'
	},{
		id:4,
		name: '已关闭'
	},{
		id:5,
		name: '纠纷中'
	},{
		id:6,
		name: '已过期'
	},
	])
	let pageFrom = {
		pageNum: 1,
		pageSize: 10,
	}
	let total = ref()
	let grabOrderList = ref([])
	let curerentIndex = ref(0)
	const timers = ref({}); //倒计时
	onLoad((value)=>{
		if(value.currentStatus){
			pageFrom.currentStatus = value.currentStatus
			list.value.forEach(item=>{
				if(item.id==value.currentStatus){
					curerentIndex.value = item.id
				}
			})
		}
		// getGrabList()
	})
	onShow(()=>{
		pageFrom.pageNum = 1
		// curerentIndex.value = 0
		delete pageFrom.orderId 
		delete pageFrom.createTime
		grabOrderList.value = []
		seahData.value = ''   //清空输入框
		getGrabList()
	})
	
	onUnmounted(() => {
		Object.values(timers.value).forEach(timer => clearInterval(timer));
	});
	
	onUnload(()=>{
		grabOrderList.value = []
		pageFrom.pageNum = 1
		pageFrom.pageSize = 10
	})
	const getGrabList = ()=>{
		uni.showLoading({
			mask: true
		});
		
		let cityJinWei = {
			...dataGong(),
			...pageFrom
		}
		let cenShi = sortAndFormatParams(cityJinWei) //请求序列化并变成字符串
		let combineTrue = combine(cenShi, cityJinWei.timestamp)
		
		grabList(cityJinWei,combineTrue).then(res=>{
			console.log('res',res)
			uni.hideLoading()
			total.value = res.total
			grabOrderList.value = [
				...grabOrderList.value,
				...res.data
			]
			grabOrderList.value = uniqueById(grabOrderList.value)
			grabOrderList.value.forEach(item=>{
				updateCountdown(item)
			})
			
		}).catch(err=>{
			uni.hideLoading()
		})
	}
	
	// 更新倒计时
	const updateCountdown = (item) => {
		// 非待支付订单不处理倒计时
		if (item.currentStatus != 0) {
			clearTimer(item.id);
			item.showCountdown = false;
			return;
		}
		const countdown = calculateCountdown(item);
		if (countdown <= 0) {
			handleCountdownEnd(item);
			return;
		}
	
		item.countdown = countdown;
		item.showCountdown = true;
	
		timers.value[item.id] = setInterval(() => {
			item.countdown -= 1000;
			if (item.countdown <= 0) {
				console.log('时间:',item.countdown);
				handleCountdownEnd(item);
			}
		}, 1000);
	};
	
	// 计算倒计时时间
	const calculateCountdown = (value) => {
		console.log('value,,,,,',value);
		const now = new Date().getTime();
		const createDateTime = new Date(value.orderCreateTime).getTime();
		const countdownTime = (value.expireTime) * 1000;
		return countdownTime - (now - createDateTime);
	};
	
	// 处理倒计时结束
	const handleCountdownEnd = (item) => {
		clearTimer(item.id);
		item.showCountdown = false;
		if (item.currentStatus == 0) {
			console.log(item);
			item.currentStatus = 5; // 设置为已过期
		}
	};
	
	// 清除定时器
	const clearTimer = (id) => {
		if (timers.value[id]) {
			clearInterval(timers.value[id]);
			delete timers.value[id];
		}
	};
	
	// 滑块
	const clickList = (e)=>{
		curerentIndex.value = e.id
		grabOrderList.value = []
		seahData.value = ''   //清空输入框
		if(e.id==0){
			pageFrom = {
				pageNum: 1,
				pageSize: 10,
			}
		} else {
			pageFrom = {
				pageNum: 1,
				pageSize: 10,
			}
			pageFrom.currentStatus = e.id
		}
	    delete pageFrom.createTime
		getGrabList()
	}
	// 下拉刷新
	onPullDownRefresh(()=>{
		grabOrderList.value = []
		pageFrom.pageNum = 1
		getGrabList()
		setTimeout(()=>{
			uni.stopPullDownRefresh() 
		},500)
	})
	// 上滑加载
	onReachBottom(()=>{
		if(total.value==grabOrderList.value.length){
			uni.showToast({
				title: '暂无更多订单',
				icon: "none",
			})
			return
		}
		pageFrom.pageNum+=1
		getGrabList()
	})
	
	const report = (value)=>{
		grabOrderList.value = []
		uni.navigateTo({
			url:`/pagesA/grab/report?id=${value.orderId}&merchantId=${value.storeUserId}`
		})
	}
	
	const orderFailedTo = (value) => {
		uni.showModal({
			title: '提示',
			content: '确定要手动失败该订单吗？',
			success: function (res) {
				if (res.confirm) {
					let cityJinWei = {
						orderId: value.orderId,
						...dataGong()
					}
					let cenShi = sortAndFormatParams(cityJinWei) //请求序列化并变成字符串
					let combineTrue = combine(cenShi, cityJinWei.timestamp)
					orderFailed(cityJinWei,combineTrue).then(res=>{
						uni.showToast({
							title: '操作成功',
							icon: "none",
						})
						value.currentStatus = 3
					}).catch(err=>{
						
					})
				}
			}
		});
	}
	
	const toReport = (value)=>{
		let orderId = value.orderId
		if(value.currentStatus=='4'){
			grabOrderList.value = []
			uni.navigateTo({
				url:`/pagesA/grab/dispute?id=${orderId}&merchantId=${value.storeUserId}`
			})
		}else if(value.currentStatus=='1'||value.currentStatus=='2'||value.currentStatus=='3'||value.currentStatus=='5' ){
			grabOrderList.value = []
			uni.navigateTo({
				url:`/pagesA/grab/detail?id=${orderId}&currentStatus=${value.currentStatus}&merchantId=${value.storeUserId}`
			})
		}
	}
	
	const searchChanmge = (e)=>{
		console.log(e);    //e用户输入内容
		pageFrom.orderId = e
		pageFrom.pageNum = 1
		pageFrom.pageSize = 10
		if(e=='' || e==null || e==undefined || !e){
			delete pageFrom.orderId
		}
		grabOrderList.value = []
		curerentIndex.value = 0
		delete pageFrom.currentStatus 
		getGrabList()
		
	}
	
	const customChange = (e)=>{
		pageFrom.orderId = e
		pageFrom.pageNum = 1
		pageFrom.pageSize = 10
		if(e=='' || e==null || e==undefined || !e){
			delete pageFrom.orderId
		}
		grabOrderList.value = []
		curerentIndex.value = 0
		delete pageFrom.currentStatus
		getGrabList()
	}
	
	const confirm = (e) => {
		grabOrderList.value = []
		pageFrom.pageNum = 1
		pageFrom.pageSize = 10
		function formatDate(timestamp) {
			const date = new Date(timestamp);
			const year = date.getFullYear();
			let month = String(date.getMonth() + 1).padStart(2, '0');
			let day = String(date.getDate()).padStart(2, '0');

			return `${year}-${month}-${day}`;
		}
		dataSelst.value = formatDate(e.value)
		console.log(dataSelst.value);
		pageFrom.createTime = dataSelst.value
		getGrabList()
	}
	const cancel = () => {
	
	}
	const focus = ()=>{
		datetimePicker.value.open()
	}
	
	// 去重
	const uniqueById = (arr) => {
	  const seen = new Set();
	  return arr.filter(item => {
	    const key = item.orderId;
	    if (seen.has(key)) {
	      return false;
	    }
	    seen.add(key);
	    return true;
	  });
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f9f9f9;
	}
	::-webkit-scrollbar {
	    display: none;
	}
	::v-deep .uv-tabs__wrapper__nav__item {
		position: relative;
		flex: 1 1 1 !important;
	}
	.eps {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}
	.fw {
		font-weight: bold;
		font-size: 30rpx;
	}
</style>
